/*
 * Copyright 2010-2011 Mike Novak <michael.novakjr@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.codeversed.plugins.buzz.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

import org.json.JSONObject;

import java.lang.ref.WeakReference;

import com.codeversed.plugins.buzz.R;
import com.codeversed.plugins.buzz.provider.BuzzContentProvider;
import com.codeversed.plugins.buzz.util.BuzzUtils;
import com.codeversed.plugins.buzz.util.Constants;
import com.codeversed.plugins.buzz.util.HttpUtils;
import com.codeversed.plugins.buzz.util.ImageUtils;

public class BuzzComposeActivity extends Activity {
    protected static final int DIALOG_POSTING = 0x1;
    protected static final int DIALOG_POST_ERROR = 0x2;
    protected static final int DIALOG_NO_NETWORK = 0x3;
    protected static final int DIALOG_NO_TEXT = 0x4;
    
    private String mToken;
    private String mTokenSecret;
    private EditText mPostEdit;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buzzcompose);
        
        ImageView avatarView = (ImageView) findViewById(R.id.compose_avatar_view);
        mPostEdit = (EditText) findViewById(R.id.activity_post_entry);
        
        Bitmap avatarImage = ImageUtils.roundBitmapCorners(getResources(), R.drawable.ic_blank_avatar, 15);
        avatarView.setImageBitmap(avatarImage);
        
        SharedPreferences prefs = getSharedPreferences("buzz_oauth.prefs", Context.MODE_PRIVATE);
        mToken = prefs.getString(Constants.PREF_TOKEN, "");
        mTokenSecret = prefs.getString(Constants.PREF_TOKEN_SECRET, "");
        
        AvatarDownloadTask task = new AvatarDownloadTask(avatarView, mToken, mTokenSecret);
        task.execute(Constants.BUZZ_PROFILE_SELF);
    }
    
    @Override
    protected Dialog onCreateDialog(int id, Bundle args) { 
        AlertDialog.Builder builder;
               
        switch (id) {
        case DIALOG_POSTING:
            ProgressDialog dialog = new ProgressDialog(this);
    		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    		dialog.setMessage(getString(R.string.post_activity_label));
    		return dialog;
    	case DIALOG_POST_ERROR:
    	    builder = new AlertDialog.Builder(this);
    	    builder.setTitle(getString(R.string.post_activity_error_title));
    	    builder.setMessage(getString(R.string.post_activity_error_text));
    	    builder.setNeutralButton(R.string.confirm_dialog, new DialogInterface.OnClickListener() {
    	        public void onClick(DialogInterface dialog, int which) {
    	            dialog.dismiss();
    	        }
    	    });
    	    return builder.create();
    	case DIALOG_NO_NETWORK:
    	    builder = new AlertDialog.Builder(this);
    	    builder.setTitle(getString(R.string.no_network_title));
    	    builder.setMessage(getString(R.string.no_network_message));
    	    builder.setNeutralButton(R.string.confirm_dialog, new DialogInterface.OnClickListener() {
    	        public void onClick(DialogInterface dialog, int which) {
    	            dialog.dismiss();
    	        } 
    	    });
    	    return builder.create();
    	case DIALOG_NO_TEXT:
    	    builder = new AlertDialog.Builder(this);
    	    builder.setTitle(getString(R.string.no_post_content_title));
    	    builder.setMessage(getString(R.string.no_post_content_text));
    	    builder.setNeutralButton(R.string.confirm_dialog, new DialogInterface.OnClickListener() {
    	        public void onClick(DialogInterface dialog, int which) {
    	            dialog.dismiss();
    	        }    
    	    });
    	    return builder.create();
    	default:
    	    Log.e(Constants.LOG_TAG, "Dialog request not recognized: " + id);
    	    return null;
        }        
    }
    
    public void onCancel(View view) {
        finish();
    }
    
    public void onPost(View view) {
        /* check for an internet connection. */
        if (!HttpUtils.isConnectedToNetwork(this)) {
            showDialog(DIALOG_NO_NETWORK);
            return;
        }
        
        if (TextUtils.isEmpty(mPostEdit.getText().toString().trim())) {
            showDialog(DIALOG_NO_TEXT);
            return;
        }
        
        showDialog(DIALOG_POSTING);
        
        ActivityPostTask task = new ActivityPostTask(this);
        task.execute(mPostEdit.getText().toString(), mToken, mTokenSecret);
    }
    
    class AvatarDownloadTask extends AsyncTask<String, Void, Bitmap> {
        private final WeakReference<ImageView> mViewRef;
        private String mToken;
        private String mTokenSecret;
        
        public AvatarDownloadTask(ImageView view, String token, String tokenSecret) {
            mViewRef = new WeakReference<ImageView>(view);
            mToken = token;
            mTokenSecret = tokenSecret;
        }
        
        @Override
        protected Bitmap doInBackground(String... params) {
            try {
                Bundle httpParams = new Bundle();
                httpParams.putString("alt", "json");
                
                OAuthConsumer consumer = new CommonsHttpOAuthConsumer("anonymous", "anonymous");
                consumer.setTokenWithSecret(mToken, mTokenSecret);
                
                String resp = HttpUtils.openUrl(params[0], HttpUtils.METHOD_GET, null, httpParams, null, consumer);
                JSONObject profile = new JSONObject(resp);
                String url = profile.getJSONObject("data").getString("thumbnailUrl");
                
                return ImageUtils.downloadBitmap(url);
            } catch (Exception e) {
                Log.e(Constants.LOG_TAG, "Error retrieving user's avatar: " + e.toString());
                return null;
            }
        }
        
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (isCancelled()) {
                bitmap = null;
            }
            
            if (bitmap == null) {
                return;
            }
            
            ImageView imageView = mViewRef.get();
            
            if (imageView != null) {
                Bitmap roundedImage = ImageUtils.roundBitmapCorners(bitmap, 15);
                imageView.setImageBitmap(roundedImage);
                imageView.setVisibility(ImageView.VISIBLE);
            }
        }
    }
    
    class ActivityPostTask extends AsyncTask<String, Void, Integer> {
        private final WeakReference<BuzzComposeActivity> mActivityRef;
        
        public ActivityPostTask(BuzzComposeActivity act) {
            mActivityRef = new WeakReference<BuzzComposeActivity>(act);
        }
        
        @Override
        protected Integer doInBackground(String... params) {
            try {
                boolean result = BuzzUtils.composeNewActivity(params[0], params[1], params[2]);
                
                if (result) {
                    return 1;
                } else {
                    return 0;
                }
            } catch (Exception e) {
                Log.e(Constants.LOG_TAG, "Exception posting activity: " + e.toString());
                return 0;
            }
        }
        
        @Override
        protected void onPostExecute(Integer status) {
            BuzzComposeActivity act = mActivityRef.get();

            if (act == null) {
                return;
            }
            
            if (status == 1) {
                act.getContentResolver().notifyChange(BuzzContentProvider.CONTENT_URI, null);
                act.removeDialog(BuzzComposeActivity.DIALOG_POSTING);
                act.finish();
            } else {
                act.removeDialog(BuzzComposeActivity.DIALOG_POSTING);
                act.showDialog(BuzzComposeActivity.DIALOG_POST_ERROR);
            }
        }
    }
}
